package conf

import (
	"pan/common/exception"
	"pan/common/util"
	"time"
)

var GlobalToken *Token

type Token struct {
	Userid    string `json:"userid"`
	Tokenid   string `json:"tokenid"`
	Expires   int64  `json:"expires"`
	ExpiresAt string `json:"expires_at"`
}

func (t *Token) IsEmpty() bool {
	return t.Tokenid == ""
}

func (t *Token) SetExpires(expires int64) {
	expireAt := time.Now().Add(time.Duration(expires * int64(time.Second)))
	t.ExpiresAt = util.DateForamt(&expireAt, util.DATETIME_FMT)
	t.Expires = expires
}

func (t *Token) Load() {
	filePath := util.TokenFilePath()
	if !util.IsExists(filePath) {
		return
	}
	util.LoadJsonFile(filePath, t)
}

func (t *Token) Save() error {
	filePath := util.TokenFilePath()
	if filePath == "" {
		return exception.NewExpectError("token recored dir not found")
	}
	return util.WriteStruct(filePath, t)
}

func NewToken() *Token {
	return &Token{}
}

func IsTokenValid() bool {
	if GlobalToken == nil {
		return false
	}
	if GlobalToken.Tokenid == "" {
		return false
	}
	expireAtTime, err := util.ParseDate(GlobalToken.ExpiresAt, util.DATETIME_FMT)
	if err != nil {
		return false
	}
	return time.Now().Before(expireAtTime)
}
